package com.jwell.panprovider.ui.activity

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.jwell.cargoapp.ui.base.MVPBaseActivity
import com.jwell.panprovider.R
import com.jwell.panprovider.contract.ProviderRegisterContract
import com.jwell.panprovider.entity.AppCocntractDetailDto
import com.jwell.panprovider.entity.AppContratcListDto
import com.jwell.panprovider.entity.SearchDriverBean
import com.jwell.panprovider.entity.ValMsgDto
import com.jwell.panprovider.model.ProviderRegisterModel
import com.jwell.panprovider.presenter.ProviderRegisterPresenter
import com.jwell.panprovider.ui.custom.LicensePlateUtils
import com.jwell.panprovider.ui.dialog.PreRegisterDialog
import kotlinx.android.synthetic.main.activity_provider_register.*

/**
 * 供应预登记
 * @author 765773123
 */
class ProviderRegisterActivity : MVPBaseActivity<ProviderRegisterPresenter>(), ProviderRegisterContract.View, View.OnClickListener {

    private var detailRequest = ProviderRegisterModel.Detail()
    private var provideData = ProviderRegisterModel.RequestData()
    //选择司机
    private val CHOOSE_DRIVER = 3
    private var popupWindow: PopupWindow? = null
    //合同号
    private var mtrlOrderNo: String? = null
    //计划明细id
    private var fuelDetailId: Int? = null


    override fun createPresenter(): ProviderRegisterPresenter? {
        return ProviderRegisterPresenter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        setContentView(R.layout.activity_provider_register)
        initToolBar("预登记", true, null)
        setListener()
        intent?.let {
            detailRequest.fuelDetailId = it.getIntExtra("fuelDetailId", 0)
            detailRequest.mtrlOrderNo = it.getStringExtra("mtrlOrderNo")
        }
        showProgress("", true)
        presenter?.appGetContractDetail(detailRequest)
    }

    private fun setListener() {
        text_chooseCarNum.setOnClickListener(this)
        text_driverName.setOnClickListener(this)
        text_driverPhone.setOnClickListener(this)
        btn.setOnClickListener(this)
        rl_item21.setOnClickListener(this)
        rl_item22.setOnClickListener(this)
        edit_remark.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                s?.let {
                    if (it.length > 15) {
                        val ss = it.toString().subSequence(0, 15)
                        edit_remark.setText(ss)
                    }
                }
            }

        })
    }

    //设置计量类别选中项
    private fun setLabelSelected(c1: Boolean, c2: Boolean) {
        rl_item21.isSelected = c1
        rl_item22.isSelected = c2
        setTextColor(c1, text_label21, image_tick_21)
        setTextColor(c2, text_label22, image_tick_22)
    }

    private fun setTextColor(isChecked: Boolean, textView: TextView, imageView: ImageView) {
        when (isChecked) {
            true -> {
                textView.setTextColor(application.resources.getColor(R.color.black))
                imageView.visibility = View.VISIBLE
            }
            false -> {
                textView.setTextColor(application.resources.getColor(R.color.c999999))
                imageView.visibility = View.GONE
            }
        }
    }

    override fun setDetail(data: AppCocntractDetailDto) {
        mtrlOrderNo = data.mtrlOrderNo ?: ""
        fuelDetailId = data.fuelDetailId
        text_contractInfo.text = mtrlOrderNo + "(" + (data.mtrlDescr ?: "") + ")"
        text_carNum1.text = data.monthPlanNum.toString() + "吨"
        text_carNum2.text = data.earlyPlan.toString() + "车/" + data.firsT_THIRD_QUANTITY + "吨"
        text_carNum3.text = data.midPlanNum.toString() + "车/" + data.middlE_THIRD_QUANTITY + "吨"
        text_carNum4.text = data.latePlanNum.toString() + "车/" + data.lasT_THIRD_QUANTITY + "吨"
        text_info1.text = data.monthSupplyCar.toString() + "车/" + data.monthSupplyTon.toString() + "吨"
        text_info2.text = data.earlySupplyCar.toString() + "车/" + data.earlySupplyTon.toString() + "吨"
        text_info3.text = data.midSupplyCar.toString() + "车/" + data.midSupplyTon.toString() + "吨"
        text_info4.text = data.lateSupplyCar.toString() + "车/" + data.lateSupplyTon.toString() + "吨"
        text_provide_info.text = "指定" + data.appointCarCount + "车、可抢" + data.snatchingCount + "车"
        text_sendCom.text = data.forwardingUnit ?: ""
        text_receiptCom.text = data.receivingUnit ?: ""
        text_chang_jia.text = data.manufactureR_DETAIL ?: ""
        text_chang_di.text = data.producinG_SIMPLE ?: ""
        if ("钢企球团厂" == text_receiptCom.text.toString()) {
            ll_measure.visibility = View.VISIBLE
            setLabelSelected(true, false)
        }
        if (data.isUnlimited) {
            text_can_provide_num.text = "剩余可供应  不限"
            text_provide_info.visibility = View.GONE
        } else {
            text_can_provide_num.text = "剩余可供应" + data.supplyCount + "车"
            text_provide_info.visibility = View.VISIBLE
        }
        if (data.supplyCount <= 0 && !data.isUnlimited) {
            btn.visibility = View.GONE
            ll_step2.visibility = View.GONE
            ll_carNum.visibility = View.GONE
            ll_driverName.visibility = View.GONE
            ll_driverPhone.visibility = View.GONE
            v111.visibility = View.GONE
            toast("登记名额已用完，禁止再次登记")
        } else {
            btn.visibility = View.VISIBLE
            ll_step2.visibility = View.VISIBLE
            ll_carNum.visibility = View.VISIBLE
            ll_driverName.visibility = View.VISIBLE
            ll_driverPhone.visibility = View.VISIBLE
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.rl_item21 -> {
                setLabelSelected(true, false)
            }
            R.id.rl_item22 -> {
                setLabelSelected(false, true)
            }
            R.id.text_chooseCarNum -> {
                val utils = LicensePlateUtils(this@ProviderRegisterActivity, popupWindow)
                utils.showInParentDown(rL_3)
                utils.setLicenseSelectedListener { licenseNum ->
                    text_chooseCarNum.text = licenseNum
                    presenter?.checkCarNum(licenseNum)
                }
            }
            R.id.text_driverName -> {
                val intent = Intent(this@ProviderRegisterActivity, SearchActivity::class.java)
                var bundle = Bundle()
                bundle.putInt("type", CHOOSE_DRIVER)
                bundle.putInt("driverPosition", 0)
                bundle.putBoolean("canInput", true)
                intent.putExtras(bundle)
                startActivityForResult(intent, CHOOSE_DRIVER)
            }
            R.id.text_driverPhone -> {
                val intent = Intent(this@ProviderRegisterActivity, SearchActivity::class.java)
                var bundle = Bundle()
                bundle.putInt("type", CHOOSE_DRIVER)
                bundle.putInt("driverPosition", 0)
                bundle.putBoolean("canInput", true)
                intent.putExtras(bundle)
                startActivityForResult(intent, CHOOSE_DRIVER)
            }
            R.id.btn -> {
                if (text_chooseCarNum.text.isNullOrEmpty()) {
                    toast("请选择车牌号码")
                    return
                }
                if (text_driverName.text.isNullOrEmpty()) {
                    toast("请完善司机信息")
                    return
                }
                if (text_driverPhone.text.isNullOrEmpty()) {
                    toast("请完善司机信息")
                    return
                }


                provideData = ProviderRegisterModel.RequestData()
                provideData.carNum = text_chooseCarNum.text.toString()
                provideData.driverName = text_driverName.text.toString()
                provideData.driverPhone = text_driverPhone.text.toString()
                provideData.remark = edit_remark.text.toString()
                provideData.mtrlOrderNo = mtrlOrderNo
                provideData.fuelDetailId = fuelDetailId
                provideData.forwardingUnit = text_sendCom.text.toString()
                provideData.receivingUnit = text_receiptCom.text.toString()
                if (ll_measure.visibility == View.VISIBLE) {
                    if (rl_item21.isSelected) {
                        provideData.measurementMethod = 3
                    }
                    if (rl_item22.isSelected) {
                        provideData.measurementMethod = 1
                    }
                } else {
                    provideData.measurementMethod = 1
                }
                PreRegisterDialog.Builder(this, provideData)
                        .setSureOnclickListener(object : PreRegisterDialog.SusreOnclickListener {
                            override fun onClick() {
                                showProgress("", true)
                                presenter?.appSupplyRegistration(provideData)
                            }
                        }).create().show()

            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CHOOSE_DRIVER) {
                var selectedDriver: SearchDriverBean? = data?.extras?.getSerializable("selectedDriver") as SearchDriverBean?
                selectedDriver?.let {
                    if (it.driverId == 0 || it.driverId == null) {//新增
                        it.driverName?.let {
                            text_driverName.text = it
                        }
                        it.driverPhone?.let {
                            text_driverPhone.text = it
                        }
                    } else {//选择
                        text_driverName.text = it.driverName
                        text_driverPhone.text = it.driverPhone
                    }
                    //验证司机
                    it.driverPhone?.let {
                        presenter?.checkDriverPhone(it, text_driverName.text.toString())
                    }
                }
            }
        }
    }

    override fun showCheckCarNum(data: ValMsgDto) {
        when (data.state) {
            1 -> { //1、正常(无需弹警告) 2、弹出警告(可以新增) 3、弹出警告（不让新增） ,
                text_driverName.text = data.driverName
                text_driverPhone.text = data.driverPhone
            }
            2 -> {
                text_driverName.text = data.driverName
                text_driverPhone.text = data.driverPhone
                showDialog(data.msg, DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            }
            3 -> {
                showDialog(data.msg, DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                    val utils = LicensePlateUtils(this@ProviderRegisterActivity, popupWindow)
                    utils.showInParentDown(rL_3)
                    utils.setLicenseSelectedListener { licenseNum ->
                        text_chooseCarNum.text = licenseNum
                        presenter?.checkCarNum(licenseNum)
                    }
                }, null)
            }
        }
    }

    override fun showCheckDriverPhone(isNew: Boolean, phone: String, name: String?) {
        if (isNew) {
            if (name == null) {
                showDialog("该驾驶员为系统新增的驾驶员，请您务必告知该驾驶员在登录卡车帮app时，默认登录账号为" + phone + "，登录密码为666666!", DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            } else {
                showDialog("驾驶员" + name + "为系统新增的驾驶员，请您务必告知该驾驶员在登录卡车帮app时，默认登录账号为" + phone + "，登录密码为666666!", DialogInterface.OnClickListener { dialog, which ->
                    dialog?.dismiss()
                }, null)
            }

        }
    }


    override fun registerSuccess() {
        text_chooseCarNum.text = ""
        text_driverName.text = ""
        text_driverPhone.text = ""
        edit_remark.setText("")
        presenter?.appGetContractDetail(detailRequest)

    }
}
